import 'dart:math';

import 'package:intl/intl.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/generated/locales.g.dart';

class DateTool {
  static String getDateStr(DateTime dt, String pattern) {
    return DateFormat(pattern).format(dt);
  }

  static String getYMD(int seconds) {
    return getDateStr(getDateTimeFrom(seconds), 'yyyyMMdd');
  }

  static String getFullYMDHM(int seconds) {
    return getDateStr(getDateTimeFrom(seconds), 'yyyy-MM-dd HH:mm');
  }

  static String getYMDStr(DateTime dt) {
    return getDateStr(dt, 'yyyyMMdd');
  }

  static String getYMDWithDash(DateTime dt) {
    return getDateStr(dt, 'yyyy-MM-dd');
  }

  static String getYMDHMWithDash(DateTime dt) {
    return getDateStr(dt, 'yyyy-MM-dd HH:mm');
  }

  static String getYMDHMSStr(DateTime dt) {
    return getDateStr(dt, 'yyyy-MM-dd HH:mm:ss');
  }

  static String getYMStr(DateTime dt) {
    return getDateStr(dt, 'yyyyMM');
  }

  static String getyyyyMMddHHmmss(DateTime dt) {
    return getDateStr(dt, 'yyyyMMddHHmmss');
  }

  /// 获取本月几号
  static int getDate() {
    return DateTime.now().day;
  }

  /// 格林尼治时间，单位：秒
  static int getTimeInSeconds(DateTime dt, {bool truncateHms = true}) {
    dt = truncateHms ? truncateHMS(now: dt) : DateTime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second);
    return getSecondsFrom(dt.millisecondsSinceEpoch);
  }

  /// 格林尼治时间，单位：秒
  static int getSecondsFrom(int milliseconds) {
    return (milliseconds / 1000).truncate();
  }

  /// 格林尼治时间(单位：秒)转为DateTime
  static DateTime getDateTimeFrom(int seconds) {
    return DateTime.fromMillisecondsSinceEpoch(seconds * 1000);
  }

  /// 两个时间的间隔天数
  static int differentInDays(DateTime start, DateTime end) {
    return start.difference(end).inDays;
  }

  ///补零
  static String zeroFill(int i) {
    return i >= 10 ? "$i" : "0$i";
  }

  /// 在指定的日期上加或减去指定的天数
  static DateTime offsetDays(DateTime input, int daysToAdd) {
    return input.add(Duration(days: daysToAdd));
  }

  /// 在指定的日期上加或减去指定的月数
  static DateTime offsetMonths(DateTime input, int monthsToAdd) {
    return DateTime(input.year, input.month + monthsToAdd);
  }


  /// 获取当月的总天数
  static int getDaysInCurrentMonth({DateTime? month}) {
    var now = month ?? DateTime.now();
    // 计算下个月1号的前一天是几号，得出结果
    return DateTime(now.year, now.month + 1, 0).day;
  }

  /// 去掉时分秒
  static DateTime truncateHMS({DateTime? now}) {
    DateTime current = now ?? DateTime.now();
    return DateTime(current.year, current.month, current.day);
  }

  static DateTime getMinDate(List<int> timestamps) {
    int m = timestamps.reduce((v, e) => min(v, e));
    return DateTime.fromMillisecondsSinceEpoch(m);
  }

  /// 判断某个日期距离指定日期（nextDay）距离的天数（length），天数默认为5天
  static bool nearNextDay(DateTime someday, {DateTime? nextDay, int length = 5}) {
    nextDay = nextDay ?? offsetDays(DateTime.now(), length);
    return differentInDays(nextDay, someday) <= length;
  }

  /// 判断当天是否在指定月份之中， month默认为当月
  static bool somedayInMonth(DateTime today, {DateTime? month}) {
    DateTime currentMonth = month ?? DateTime.now();
    DateTime start = DateTime(currentMonth.year, currentMonth.month, 1);
    DateTime end = offsetDays(start, getDaysInCurrentMonth(month: currentMonth));
    return today.compareTo(start) >= 0 && today.compareTo(end) < 0;
  }

  /// 秒转时分
  static String second2HM(int sec, {bool isEasy = true}) {
    String hm = "0${LocaleKeys.time_unit_hour.ts}0${LocaleKeys.time_unit_minute.ts}";
    if (sec > 0) {
      int h = sec ~/ 3600;
      int m = (sec % 3600) ~/ 60;
      hm = "$h${LocaleKeys.time_unit_hour.ts}$m${LocaleKeys.time_unit_minute.ts}";
    }
    return hm;
  }

  /// 时:分:秒转秒
  static int hMS2Seconds(String hms) {
    if (hms.isEmpty || !hms.contains(':')) {
      return 0;
    }

    List<String> arr = hms.split(':');
    return int.parse(arr[0]) * 3600 + int.parse(arr[1]) * 60 + int.parse(arr[2]);
  }

  /// 秒转时分秒
  static String second2HMS(int sec, {bool isEasy = true}) {
    String hms = "00:00:00";
    if (sec > 0) {
      int h = sec ~/ 3600;
      int m = (sec % 3600) ~/ 60;
      int s = sec % 60;
      hms = "${zeroFill(h)}:${zeroFill(m)}:${zeroFill(s)}";
      if (!isEasy) {
        String hour = h <= 0 ? '' : '${zeroFill(h)}${LocaleKeys.time_unit_hour.ts}';
        String minute = m <= 0 ? '' : '${zeroFill(m)}${LocaleKeys.time_unit_minute.ts}';
        String second = s <= 0 ? '' : '${zeroFill(s)}${LocaleKeys.time_unit_second.ts}';
        hms = '$hour$minute$second';
      }
    }
    return hms;
  }

  static bool isSameDay(DateTime? a, DateTime? b) {
    if (a == null || b == null) {
      return false;
    }
    return a.year == b.year && a.month == b.month && a.day == b.day;
  }

  static bool isInRange(DateTime? start, DateTime? end, DateTime input) {
    if (start == null || end == null) {
      return false;
    }

    return start.millisecondsSinceEpoch <= input.millisecondsSinceEpoch && end.millisecondsSinceEpoch >= input.millisecondsSinceEpoch;
  }

  /// 将yyyyMMddHHmmss格式的日期转换成yyyy-MM-dd HH:mm:ss格式
  static String toFullYMDHMS(String ymdhms) {
    String dateWithT = '${ymdhms.substring(0, 8)}T${ymdhms.substring(8)}';
    return DateTool.getYMDHMSStr(DateTime.parse(dateWithT));
  }

  /// 将yyyyMMddHHmmss格式的日期转换成yyyy-MM-dd HH:mm格式
  static String toFullYMDHM(String ymdhms) {
    String dateWithT = '${ymdhms.substring(0, 8)}T${ymdhms.substring(8)}';
    return DateTool.getYMDHMWithDash(DateTime.parse(dateWithT));
  }

  /// 格式化为小时:分， 例如小时:分
  static hsFormat(DateTime dt) {
    return DateFormat('HH:mm').format(dt);
  }

  /// 格式化为月/日， 例如09/01
  static mdFormat(DateTime dt) {
    return DateFormat('MM/dd').format(dt);
  }

  /// 格式化为年/月/日， 例如2024/01/01
  static ymdFormat(DateTime dt) {
    return DateFormat('yyyy/MM/dd').format(dt);
  }

  /// 格式化为年/月/日 小时:分， 例如2024/01/01 12:10
  static ymdhmFormat(DateTime dt) {
    return DateFormat('yyyy/MM/dd HH:mm').format(dt);
  }
}
